Ext.define('Sencha.controller.DictionarySourceController', {
    extend: 'Ext.app.Controller',

    config: {
        // Flags used to check state of search filter buttons
        engDictionaryButtonOn: true,
        iwaDictionaryButtonOn: true,
        
        // Dictionary Target & Source property
        
        sourceWordfield : "",
        partOfSpeechField : "",
        inflectionField : "",
        disambiguationField : "",
        targetWordField : "",
        detailedEntryField : "",
        noteField : "",
        
        
        //metadata form
        currentDate: "",
        currentTime: "",
        currentLocation: "",
        recordingDevice: "",
        
        
        //speaker form
        speakerName: "",
        speakerDOB: "",
        speakerGender: "",
        speakerComment: "",
        
        
        
        
        //collector form
        collectorName: "",
        collectorDOB: "",
        collectorGender: "",
        collectorComment: "",
        
        
        
        //id collection
        targetId: "",
        collectorId: "",
        speakerId: "",
        
        
        
        refs: {
           main: 'dictionarysourcenavigationview',
           //addDictionaryEntryButton: 'button[text="+"]',
           addImageButtonRef: 'button[cls=addImageButtonCls]',
           audioRecordButtonRef: 'button[cls=audioRecordButtonCls]',
           dictionaryEntryButton: 'button[id=dictionaryEntryButton]',
           dictionaryDeleteButton: 'button[id=deleteDictionaryButton]',
           //editDictionaryButton: 'button[cls=editDictionaryButton]',
           dictionarySearchField: 'searchfield[name=dictionarySearchField]',
           dictionarySourceListView: 'dictionarysourcelistview',
      
           //engDictionaryButton: 'button[text="ENG"]',
           engDictionaryButton: 'button[id=engDictionaryButtonId]',
           //iwaDictionaryButton: 'button[text="IWA"]',
           iwaDictionaryButton: 'button[id=iwaDictionaryButtonId]',
           dictionaryForm: 'fieldset[id="dicFormFieldSet"]',
           dicMetadaForm: 'fieldset[id="dicMetadataFieldset"]',
           
           //speaker
           
           speakerNameField: 'fieldset[id="speakerNameFieldset"]',
           speakerGenderField: 'radiofield[name="speakerGender"]',
           speakerCommentField: 'fieldset[id="speakerCommentFieldset"]',
           
           
           //collector
           
           collectorNameField: 'fieldset[id="collectorNameFieldset"]',
           collectorGenderField: 'radiofield[name="collectorGender"]',
           collectorCommentField: 'fieldset[id="collectorCommentFieldset"]',
           
      
        },
        
     
        control: {
            'dictionarySourceListView': {
                disclose: 'showDetail',
                select: 'playAudio'
            },
            'dictionaryEntryButton':{        
                tap:'onDictionaryEntryButtonTap'
            },
            'dictionarySearchField':{        
                keyup:'filterDictionarySearch',
                clearicontap:'clearDictionarySearchFilter'
            },
            'engDictionaryButton' :{
           		tap: 'toggleEngDictionaryButton',
                show: 'showDictionaryAddButton'
            },
            'iwaDictionaryButton' :{
           		tap: 'toggleIwaDictionaryButton'
            },
            'dictionarysourcenavigationview':{
            	back:'onBackButton'
           },
           'addImageButtonRef':{
                tap:'onAddImageTap'
           },
           'audioRecordButtonRef':{
                tap:'onAudioRecordTap'
           },
           'button[id="dicMetadataButton"]':{
           		tap:'showMetadataForm'
           },
           'button[id="collectorButton"]':{
           		tap:'showCollectorForm'
           },
           'button[id="speakerButton"]':{
           		tap:'showSpeakerForm'
           },
           'button[id="deleteDictionaryButton"]':{
           		tap:'deleteDictionaryEntry'
           }
        }
    },

    // Handle navigation bar button taps ie. add new dict. entry, edit dict. entry, done (eidting, adding)
    onDictionaryEntryButtonTap: function() {
        var innerItems = this.getMain().getInnerItems();
        var currentItem = innerItems[innerItems.length-1].xtype; // get current screen/component
        

        
        switch(currentItem)
        {
            // if this is the dictionary list view then add entry
            case "dictionarycontainerlist":
                console.log("add dict entry");
                this.getDictionaryEntryButton().setText('DONE');
                this.showForm();
                break;
            // if this is the dictionary detail view then edit entry
            case "dictionarytargetdetailview":
                console.log("edit dict entry");
                this.getDictionaryEntryButton().setText('DONE');
                this.editForm();
                break;
            case "dicmetadataformview":
            	//saving data on metadata form
            	
            	this.setCurrentDate(this.getDicMetadaForm().getComponent('dateField').getValue());
            	this.setCurrentTime(this.getDicMetadaForm().getComponent('timeField').getValue());
            	this.setCurrentLocation(this.getDicMetadaForm().getComponent('recordingDeviceField').getValue());
            	this.setRecordingDevice(this.getDicMetadaForm().getComponent('locationField').getValue());            	
            	
            	this.getDictionaryEntryButton().setText('DONE');
            	this.getMain().pop();
            	
                	
            	
            	break;
            	
            case "speakerformview":

            	this.setSpeakerName(this.getSpeakerNameField().getComponent('speakerNameField').getValue());
            	
            	this.setSpeakerDOB(this.getSpeakerNameField().getComponent('speakerDOBField').getFormattedValue());
            	    	
            	this.setSpeakerGender(this.getSpeakerGenderField().getGroupValue());
        	
            	this.setSpeakerComment(this.getSpeakerCommentField().getComponent('speakerCommentField').getValue());
            
            	this.getMain().pop();
            	break;
            	
            case "collectorformview":
            	this.setCollectorName(this.getCollectorNameField().getComponent('collectorNameField').getValue());
            	
            	this.setCollectorDOB(this.getCollectorNameField().getComponent('collectorDOBField').getFormattedValue());
            	
            	this.setCollectorGender(this.getCollectorGenderField().getGroupValue());
            	
            	this.setCollectorComment(this.getCollectorCommentField().getComponent('collectorCommentField').getValue());
            	            	
            	this.getMain().pop();
            	
            	break;
            	
            // if this is the dictionary detail view then edit entry
            case "dictionaryformview":
                var previousItem = innerItems[innerItems.length-2].xtype;
                
                // if add dictionary entry
                if (previousItem=="dictionarycontainerlist") {
                    // Save new entry
                    console.log("save new dict entry");
           
                    // call fn to save new entry
                    this.saveForm();
           
                    this.getDictionaryEntryButton().setText('+');
                    
                    this.getMain().pop();
                } 
                // if edit dictionary entry
                else {
                    // Save existing entry
                    console.log("save existing dict entry");
                    
                    this.getDictionaryEntryButton().setText('EDIT');
                    // call fn to save existing entry
                    // ...
                    
                    this.updateForm();
                    
                    this.getMain().pop();
                }
                break;
        }
    },
    
    //fired when back button is pressed on dictionary 
    //
    onBackButton: function(){
        var innerItems = this.getMain().getInnerItems();
        var currentItem = innerItems[innerItems.length-2].xtype; // get screen/component we came from
		

		
        // This code when using string comparison slows the back buttons respone time by about a second!!!
        // Not usre this will work once we start using the other tabs ie. onBackButton will capture
        // all back button events probably?
        switch(currentItem)
        {
            // if the previous screen was the list view
            case "dictionarycontainerlist":
          
                this.getDictionaryEntryButton().show();
                this.getDictionaryEntryButton().setText('+');
                break;
            // if the previous screen was the detail view
            case "dictionarytargetdetailview":
                
                this.getDictionaryEntryButton().setText('EDIT');
                break;
            
            case "dictionaryformview":
            	this.getDictionaryEntryButton().setText('DONE');
        }
    },
    
    //show detail view for specific dictionary source word
    //
    showDetail: function(list, record) {
        
        //on this function, we are required to pass the data to dictionarytargetdetailview
        // in the past, we use 
        //      data: record.getData()
        //      the meaning of above code is getting the data from the selected record on list view
        // however the association is not working at the moment
      
        this.getDictionaryEntryButton().setText('EDIT');
        
        // Get associated DictionaryTarget record using dictionaryTargetId foreign key
        var associatedRecord = Ext.getStore("DictionaryTargets").getById( record.get('dictionaryTargetId') );
        
     
        
        
        this.getMain().push({
            xtype: 'dictionarytargetdetailview',
            
            data: {
                dictionaryTargetId: record.get('dictionaryTargetId'),
                dictionarySourceId: record.get('id'),
                targetWord: record.get('targetWord'),
                inflection: record.get('inflection'),
                detailedEntry: associatedRecord.get('detailedEntry'),
                imageURL: associatedRecord.get('imageURL') ? '<div class="dictImage"><img src="' + associatedRecord.get('imageURL') + '"/></div>' : ''
            }
        });
           
        if( record.get('isEditable') == "false"){
           this.getDictionaryEntryButton().hide();
           
	    }        
    },
    

    
    //showing add form for dictionary
   	showForm : function(){
		

        this.setSourceWordfield("");
        this.setPartOfSpeechField("");
        this.setInflectionField("");
        this.setDisambiguationField("");
        this.setTargetWordField("");
        this.setDetailedEntryField("");
        this.setNoteField("");
        
        
        this.setTargetId("");
        
        //metadata form
        
		//Getting the current date and time
    	
    	var d = new Date();
    	var curr_date = d.getDate();
    	var curr_month = d.getMonth() + 1; //months are zero based
    	var curr_year = d.getFullYear();
    
    	curr_full_date = curr_date + "/" + curr_month + "/" + curr_year;
    	
    	var curr_hour = d.getHours();
    	var curr_min = d.getMinutes();
    	var curr_sec = d.getSeconds();
    	
    	curr_full_time = curr_hour + ":" + curr_min + ":" + curr_sec;
    	
    	var deviceName = device.name;
        
        this.setCurrentDate(curr_full_date);
        this.setCurrentTime(curr_full_time);
        this.setCurrentLocation(deviceName);
        this.setRecordingDevice(geo.getLatitude() + ", " + geo.getLongitude());
        
        //speaker form
        this.setSpeakerName("");
        this.setSpeakerDOB("");
        this.setSpeakerGender("");
        this.setSpeakerComment("");
        
        //collector form
        this.setCollectorName("");
        this.setCollectorDOB("");
        this.setCollectorGender("");
        this.setCollectorComment("");
   
		

    	this.getMain().push({
    		xtype: 'dictionaryformview'			                    
        });
        
        
        this.getDictionaryDeleteButton().hide();
   	},
   	
   	deleteDictionaryEntry : function(){
   	
		var dictionarySourceStore = Ext.getStore("DictionarySources");
		var dictionaryTargetStore = Ext.getStore("DictionaryTargets");
		var speakerStore = Ext.getStore("Speakers");
		var collectorStore = Ext.getStore("Collectors");
		
		var sourceModel = dictionarySourceStore.getById(this.getDictionaryForm().getComponent('sourceIdField').getValue());
	   	
	   	dictionarySourceStore.remove(sourceModel);
	   	dictionarySourceStore.sync();

		var dicTargetId = this.getDictionaryForm().getComponent('targetIdField').getValue();
	 	
	   	if( dictionarySourceStore.find("dictionaryTargetId", dicTargetId) == -1){
	   		var targetModel = dictionaryTargetStore.getById(dicTargetId);
	   		
	   		dictionaryTargetStore.remove(targetModel);
	   		dictionaryTargetStore.sync();
	   		
	   		var dicSpeakerId = this.getDictionaryForm().getComponent('speakerIdField').getValue();
	   		var dicCollectorId = this.getDictionaryForm().getComponent('collectorIdField').getValue();
	   		
	   		if(dictionaryTargetStore.find("speakerId", dicSpeakerId) == -1){
	   			var speakerModel = speakerStore.getById(dicSpeakerId);
	   			
	   			speakerStore.remove(speakerModel);
	   			speakerStore.sync();
	   		}
	   		
	   		if(dictionaryTargetStore.find("collectorId", dicCollectorId) == -1){
	   			var collectorModel = collectorStore.getById(dicCollectorId);
	   			
	   			collectorStore.remove(collectorModel);
	   			collectorStore.sync();
	   		}
	   		
	   	}
	   	
   		this.getDictionaryEntryButton().setText('+');
   		this.getMain().pop(2);
   		//this.getMain().pop();
   		//this.getMain().pop();	
  
   	   	
   	},
   	editForm : function(){
   		console.log("editForm...");   
   		
   		var innerItems = this.getMain().getInnerItems();
   		var currentItem = innerItems[innerItems.length-1]; // get screen/component we came from
   		
   		var dictionaryTargetId = currentItem.getData()['dictionaryTargetId'];
   		var dictionarySourceId = currentItem.getData()['dictionarySourceId'];
   		
   		var dictionaryTargetStore = Ext.getStore("DictionaryTargets").getById(dictionaryTargetId);
   		var dictionarySourceStore = Ext.getStore("DictionarySources").getById(dictionarySourceId);
   		var collectorStore = Ext.getStore("Collectors").getById(dictionaryTargetStore.get('collectorId'));
   		var speakerStore = Ext.getStore("Speakers").getById(dictionaryTargetStore.get('speakerId'));
   		
   		
   		this.getMain().push({
   			xtype: 'dictionaryformview'			                    
   		});
   		
   		   	
   		this.getDictionaryForm().getComponent('sourceWordField').setValue(dictionarySourceStore.get('sourceWord'));
   		this.getDictionaryForm().getComponent('partOfSpeechField').setValue(dictionarySourceStore.get('partOfSpeech'));
   		this.getDictionaryForm().getComponent('inflectionField').setValue(dictionarySourceStore.get('inflection'));
   		this.getDictionaryForm().getComponent('disambiguationField').setValue(dictionarySourceStore.get('disambiguation'));
   		this.getDictionaryForm().getComponent('targetWordField').setValue(dictionarySourceStore.get('targetWord'));
   		this.getDictionaryForm().getComponent('detailedEntryField').setValue(dictionaryTargetStore.get('detailedEntry'));
   		this.getDictionaryForm().getComponent('noteField').setValue(dictionaryTargetStore.get('note'));
   		
   		this.getDictionaryForm().getComponent('targetIdField').setValue(dictionaryTargetId);
   		this.getDictionaryForm().getComponent('sourceIdField').setValue(dictionarySourceId);
   		this.getDictionaryForm().getComponent('speakerIdField').setValue(dictionaryTargetStore.get('speakerId'));
   		this.getDictionaryForm().getComponent('collectorIdField').setValue(dictionaryTargetStore.get('collectorId'));
   	
	
   		//setting the metadata, speaker, and collector

   	    
   		//Getting the current date and time
   		
   		var d = new Date();
   		var curr_date = d.getDate();
   		var curr_month = d.getMonth() + 1; //months are zero based
   		var curr_year = d.getFullYear();
   	
   		curr_full_date = curr_date + "/" + curr_month + "/" + curr_year;
   		
   		var curr_hour = d.getHours();
   		var curr_min = d.getMinutes();
   		var curr_sec = d.getSeconds();
   		
   		curr_full_time = curr_hour + ":" + curr_min + ":" + curr_sec;
   		
   		var deviceName = device.name;
   	    
   	    this.setCurrentDate(curr_full_date);
   	    this.setCurrentTime(curr_full_time);
   	    this.setCurrentLocation(deviceName);
   	    this.setRecordingDevice(geo.getLatitude() + ", " + geo.getLongitude());
   	    
   	    
 
   	    //speaker form
   	    this.setSpeakerName(speakerStore.get('name'));
   	    this.setSpeakerDOB(speakerStore.get('dateOfBirth'));
   	    this.setSpeakerGender(speakerStore.get('gender'));
   	    this.setSpeakerComment(speakerStore.get('comment'));
   	    
   	    //collector form
   	    this.setCollectorName(collectorStore.get('name'));
   	    this.setCollectorDOB(collectorStore.get('dateOfBirth'));
   	    this.setCollectorGender(collectorStore.get('gender'));
   	    this.setCollectorComment(collectorStore.get('comment'));
   	
   		
   		this.getDictionaryDeleteButton().show();
   		
   	},
   	
   	
   	//saving data from FORM to DATABASE
   	//calling inserForm(function) ---> this function handle database transaction
   	saveForm : function(){
   		var currentObj = this;
   		
        this.setSourceWordfield(this.getDictionaryForm().getComponent('sourceWordField').getValue());
        this.setPartOfSpeechField(this.getDictionaryForm().getComponent('partOfSpeechField').getValue());  
        this.setInflectionField(this.getDictionaryForm().getComponent('inflectionField').getValue());  
        this.setDisambiguationField(this.getDictionaryForm().getComponent('disambiguationField').getValue());  
        this.setTargetWordField(this.getDictionaryForm().getComponent('targetWordField').getValue());  
        this.setDetailedEntryField(this.getDictionaryForm().getComponent('detailedEntryField').getValue()); 
        this.setNoteField(this.getDictionaryForm().getComponent('noteField').getValue());   
		

               	
        var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
        db.transaction(function(tx){
        		
        		
        		var querySpeaker = 'INSERT INTO SPEAKER (id, name, dateOfBirth, gender, comment) VALUES (null, "'+ currentObj.getSpeakerName()+'", "'+currentObj.getSpeakerDOB()+'", "'+currentObj.getSpeakerGender()+'","'+currentObj.getSpeakerComment()+'")';
    			tx.executeSql(querySpeaker);
    			
    			var queryCollector = 'INSERT INTO COLLECTOR (id, name, dateOfBirth, gender, comment) VALUES (null, "'+ currentObj.getCollectorName()+'", "'+ currentObj.getCollectorDOB()+'", "'+currentObj.getCollectorGender()+'", "'+currentObj.getCollectorComment()+'")';
    			tx.executeSql(queryCollector);
    			
    			
    			
    			//query the speaker id
    			
    			tx.executeSql('SELECT * FROM SPEAKER', [],  function(tx,results){
    			
    			
    				currentObj.setSpeakerId(results.rows.length);
    				var dictionarySpeakerId = currentObj.getSpeakerId();
    				
    	
  
    				tx.executeSql('SELECT * FROM COLLECTOR', [], function(tx,results){
    					//query the collector id
    				
    					currentObj.setCollectorId(results.rows.length);
    					var dictionaryCollectorId = currentObj.getCollectorId();
    					
    					queryDictionaryTarget = 'INSERT INTO DICTIONARYTARGET (id, speakerId, collectorId, targetWord, detailedEntry, audioURL, imageURL, note, savedDate, savedTime, geoLocation, recordingDevice) VALUES(null,'+dictionarySpeakerId+', '+dictionaryCollectorId+', "'+currentObj.getTargetWordField() +'", "'+ currentObj.getDetailedEntryField() +'", "", "", "'+ currentObj.getNoteField() +'", "' + currentObj.getCurrentDate() +'", "' + currentObj.getCurrentTime() +'", "' + currentObj.getCurrentLocation() +'", "' + currentObj.getRecordingDevice() +'")';
    					
    	
    					tx.executeSql(queryDictionaryTarget);
    					
    					//query the target id
    					
    					tx.executeSql('SELECT * FROM DICTIONARYTARGET', [], function(tx,results){
    					              
    							currentObj.setTargetId(results.rows.length);
    					              
    					        var dictionaryTargetId = currentObj.getTargetId();
    					        
    					        
    					        var queryDictionarySource = 'INSERT INTO DICTIONARYSOURCE (id, dictionaryTargetId, sourceWord, partOfSpeech, inflection, disambiguation, targetWord) VALUES (null, '+dictionaryTargetId+', "'+ currentObj.getSourceWordfield()+'", "'+currentObj.getPartOfSpeechField()+'", "'+currentObj.getInflectionField()+'", "'+currentObj.getDisambiguationField()+'",  "'+currentObj.getTargetWordField()+'")';
    					        
    					        tx.executeSql(queryDictionarySource); 
    					        
    					        
    						}
    					, errorCB);
    					
    				
    				}
    				
    				
    				, errorCB);
    				
    			
    			}
    			
    			, errorCB);
   
        	}        
        , errorCB);
        
        this.getDictionarySourceListView().getStore().load();
        Ext.getStore("DictionaryTargets").load();
       	Ext.getStore("Collectors").load();
       	Ext.getStore("Speakers").load();
 
   	},
   	
   	
   	updateForm : function(){
   		this.setSourceWordfield(this.getDictionaryForm().getComponent('sourceWordField').getValue());
   		this.setPartOfSpeechField(this.getDictionaryForm().getComponent('partOfSpeechField').getValue());  
   		this.setInflectionField(this.getDictionaryForm().getComponent('inflectionField').getValue());  
   		this.setDisambiguationField(this.getDictionaryForm().getComponent('disambiguationField').getValue());  
   		this.setTargetWordField(this.getDictionaryForm().getComponent('targetWordField').getValue());  
   		this.setDetailedEntryField(this.getDictionaryForm().getComponent('detailedEntryField').getValue()); 
   		this.setNoteField(this.getDictionaryForm().getComponent('noteField').getValue());   
   		
   		var targetId = this.getDictionaryForm().getComponent('targetIdField').getValue(); 
   		var sourceId = this.getDictionaryForm().getComponent('sourceIdField').getValue(); 
   		var speakerId = this.getDictionaryForm().getComponent('speakerIdField').getValue(); 
   		var collectorId = this.getDictionaryForm().getComponent('collectorIdField').getValue(); 

   		
   		var dictionaryTargetStore = Ext.getStore("DictionaryTargets").getById(targetId);
   		var dictionarySourceStore = Ext.getStore("DictionarySources").getById(sourceId);
   		var speakerStore = Ext.getStore("Speakers").getById(speakerId);
   		var collectorStore = Ext.getStore("Collectors").getById(collectorId);
   		
   		dictionarySourceStore.set('sourceWord', this.getSourceWordfield());
   		dictionarySourceStore.set('partOfSpeech', this.getPartOfSpeechField());
   		dictionarySourceStore.set('inflection', this.getInflectionField());
   		dictionarySourceStore.set('disambiguation', this.getDisambiguationField());
   		dictionarySourceStore.set('targetWord', this.getTargetWordField());

   		
   		
        dictionaryTargetStore.set('targetWord', this.getTargetWordField());
        dictionaryTargetStore.set('detailedEntry', this.getDetailedEntryField());
        dictionaryTargetStore.set('note', this.getNoteField());
   		dictionaryTargetStore.set('savedDate', this.getCurrentDate());
   		dictionaryTargetStore.set('savedTime', this.getCurrentTime());
   		dictionaryTargetStore.set('geoLocation', this.getCurrentLocation());
   		dictionaryTargetStore.set('recordingDevice', this.getRecordingDevice());
   		
   		speakerStore.set('name', this.getSpeakerName());
   		speakerStore.set('dateOfBirth', this.getSpeakerDOB());
   	 	speakerStore.set('gender', this.getSpeakerGender());
   	 	speakerStore.set('comment', this.getSpeakerComment());

   		collectorStore.set('name', this.getCollectorName());
   		collectorStore.set('dateOfBirth', this.getCollectorDOB());
   		collectorStore.set('gender', this.getCollectorGender());
   		collectorStore.set('comment', this.getCollectorComment());
   		
   		
 
   		
   		Ext.getStore("DictionarySources").sync();
   		Ext.getStore("DictionaryTargets").sync();
   		Ext.getStore("Speakers").sync();
   		Ext.getStore("Collectors").sync();
 
   	
   	},
   	
 
    //play audio when list item is selected
    //
    playAudio: function(list, record) {
        
        window.requestFileSystem(
            LocalFileSystem.PERSISTENT, 
            0, 
            function(fsp) {
                // Get associated DictionaryTarget record using dictionaryTargetId foreign key
                var associatedRecord = Ext.getStore("DictionaryTargets").getById( record.get('dictionaryTargetId') );
                var audioURL = fsp.root.fullPath + "/" + associatedRecord.get('audioURL');
                
                if ( audioURL ) {
                    // Play the audio file at url
                    var my_media = new Media(
                        audioURL,
                        // success callback
                        function() {
                            console.log("playAudio():Audio Success");
                        },
                        // error callback
                        function(err) {
                            console.log("playAudio():Audio Error: "+err);
                        }
                    );
                    
                    // Play audio
                    my_media.play();
                    // release
                    //my_media.release();
                                 
                    // **** Need to release my_media ********//
                    // consider creating one for this controller and re-using it. 
                    // remove before leaving
                }
            },
            function(evt) {
                console.log(evt.target.error.code);
                var msg = 'An error occurred during capture: ' + evt.target.error.code;
                navigator.notification.alert(msg, null, 'Capture error');
            }
        );
    },
    
    
    //fired when back button is pressed on dictionary 
    //
    /*
    backNavigationView: function(){
    	if (this.getDoneDictionaryButton().isHidden() == false){
        	this.getDoneDictionaryButton().hide();
        	this.getAddDictionaryButton().show();
    	}
    },
    */
    
    // Clear dictionary search - fired when clear button pressed
    // 
    clearDictionarySearchFilter: function() {
    	var sto = this.getDictionarySourceListView().getStore();
    	sto.clearFilter();
    },
    
    /*
    dictionaryFilter: function(record) {
        console.log("in dictionaryFilter");
        
        return true;
    },
    */
    
    
    // Filter dictionary - fired when value has changed on dictionarySearchField
    // 
    filterDictionarySearch: function() {
        var sto = this.getDictionarySourceListView().getStore();
        var searchString = this.getDictionarySearchField().getValue().toLowerCase();
        var doEnglishSearch = this.getEngDictionaryButtonOn();
        var doIwaidjaSearch = this.getIwaDictionaryButtonOn();
        
        var dictFilter = new Ext.util.Filter({
            filterFn: function(item) {
                if (doEnglishSearch) {
                    var srcWord = item.get("sourceWord");
                    if ( srcWord.indexOf(searchString)==0 ) {
                        return true;     
                    } 
                }
                if (doIwaidjaSearch) {
                    var tgtWord = item.get("targetWord");
                    if ( tgtWord.indexOf(searchString)==0 ) {
                        return true;     
                    } 
                }
                
            }
        });
        
        // clear filter our
        sto.clearFilter();
        
        // filter
        console.log("before hello");
        sto.filter(dictFilter);
    },        
    
    // Toggle English search on/off
    // mdm 22.04.2012
    //
    toggleEngDictionaryButton: function() {
        // if boolean var for button state is true
        if ( this.getEngDictionaryButtonOn() ) {
            // only toggle off if the other toggle is on ie. can't have both off
            if ( this.getIwaDictionaryButtonOn() ) {
                // toggle button OFF
                this.setEngDictionaryButtonOn(false);
                this.getEngDictionaryButton().addCls('toggleButtonOff');
                // Refilter list now
                this.filterDictionarySearch();
            }
        } else {
            // toggle button ON
            this.setEngDictionaryButtonOn(true);
            // change class
            this.getEngDictionaryButton().removeCls('toggleButtonOff');
            // Refilter list now
            this.filterDictionarySearch();
        }
    },
    
    // Toggle Iwaidja search on/off
    // mdm 22.04.2012
    //
    toggleIwaDictionaryButton: function() {
        // if boolean var for button state is true
        if ( this.getIwaDictionaryButtonOn() ) {
            // only toggle off if the other toggle is on ie. can't have both off
            if ( this.getEngDictionaryButtonOn() ) {
                // toggle button OFF
                this.setIwaDictionaryButtonOn(false);
                this.getIwaDictionaryButton().addCls('toggleButtonOff');
                // Refilter list now
                this.filterDictionarySearch();

            }
        } else {
            // toggle button ON
            this.setIwaDictionaryButtonOn(true);
            // change class
            this.getIwaDictionaryButton().removeCls('toggleButtonOff');
            // Refilter list now
            this.filterDictionarySearch();

        }
    },
    
    
    showMetadataForm: function(){
    	
   		this.getDictionaryEntryButton().setText('OK');
   		
   		
    	this.getMain().push({
    		xtype: 'dicmetadataformview'			                    
    	});
  
 
    	this.getDicMetadaForm().getComponent('dateField').setValue(this.getCurrentDate());
    	this.getDicMetadaForm().getComponent('timeField').setValue(this.getCurrentTime());
    	
    	this.getDicMetadaForm().getComponent('recordingDeviceField').setValue(this.getCurrentLocation());
    	
    	this.getDicMetadaForm().getComponent('locationField').setValue(this.getRecordingDevice());
    	
    	
    },
    
    
    showCollectorForm: function() {
    	this.getMain().push({
    		xtype: 'collectorformview'			                    
    	});
    	
    	var tempDate = "";
    	if (this.getCollectorDOB() != ""){
    		tempDate = this.getCollectorDOB().split("/");
    		this.getCollectorNameField().getComponent('collectorDOBField').setValue({day  : tempDate[0], month: tempDate[1], year : tempDate[2]});
    	}
    	
    
    	
    	this.getCollectorNameField().getComponent('collectorNameField').setValue(this.getCollectorName());
    	
    	this.getCollectorGenderField().setGroupValue(this.getCollectorGender());
    	this.getCollectorCommentField().getComponent('collectorCommentField').setValue(this.getCollectorComment());
    	
    	
    },
    
    
    showSpeakerForm: function() {
    	this.getMain().push({
    		xtype: 'speakerformview'			                    
    	});
    	
    	
    	var tempDate = "";
    		if (this.getSpeakerDOB() != ""){
    			tempDate = this.getSpeakerDOB().split("/");
    			this.getSpeakerNameField().getComponent('speakerDOBField').setValue({day  : tempDate[0], month: tempDate[1], year : tempDate[2]});
    		}
    		
    	
    		
    		this.getSpeakerNameField().getComponent('speakerNameField').setValue(this.getSpeakerName());
    		
    		this.getSpeakerGenderField().setGroupValue(this.getSpeakerGender());
    		this.getSpeakerCommentField().getComponent('speakerCommentField').setValue(this.getSpeakerComment());
    	
    	
    
    },
         

    // Add image (located on Add new dictionary entry form
    //
    onAddImageTap: function() {
        console.log("in onAddIimage...");
        
        function onFileSystemFail(evt) {
           console.log(evt.target.error.code);
           var msg = 'An error occurred during capture: ' + evt.target.error.code;
           navigator.notification.alert(msg, null, 'Capture error');
        }
        
        // Move file from temporary storage to persistent storage. Uses PhoneGap File API
        // fst - temporary file system
        // srcFilename - file we want to move located on the temporary file system
        // destDir - sub dir on PERMANENT file system (optional)
        // destFilename - new filename (optional)
        // MDM 17.04.2012
        // 1. Request persistent file system (may need to get a directory here?)
        // 2. Get file from temporary file system using newly encoded filename (ie. ending in m4a)
        // 3. Move file entry from temporary file system to persistent file system
        //
        function fsCopy(fst, srcFilename, destDir, destFilename) {
           console.log("in fsCopy...");
           // Get file we want to copy using Phonegap File API
           fst.getFile (
                srcFilename, 
                {}, 
                // Success callback - get PERSISTENT file system to copy to using Phonegap File API
                function (fileEntry) {
                    window.requestFileSystem (
                        LocalFileSystem.PERSISTENT, 
                        0,
                        // Success callback - get/create sub directory if required else just move file
                        function (fsp) {
                            if ( destDir ) {
                                fsp.root.getDirectory(
                                    destDir,
                                    {create: true},
                                    // Success callback -  move file entry to persistent store 
                                    function(fspDestDir) {
                                        fileEntry.moveTo(
                                            fspDestDir,
                                            destFilename ? destFilename : srcFilename,
                                            function() {
                                                console.log("file saved");
                                            },
                                            onFileSystemFail
                                        );
                                    },
                                    onFileSystemFail
                                );
                            } else {
                                // just move file entry to persistent store root directory
                                fileEntry.moveTo(
                                    fsp.root,
                                    destFilename ? destFilename : srcFilename,
                                    function() {
                                        // need to pass this filename out?
                                        console.log("file saved");
                                    },
                                    onFileSystemFail
                                );              
                            }
                        },
                        onFileSystemFail
                    )
                }, 
                onFileSystemFail
            );
        }
           
           
           
        // Move file from temporary storage to persistent storage. Uses PhoneGap File API
        // MDM 17.04.2012
        // fromPath - path to the file we want to move that is located on the temporary file system
        // destDir - sub directory on permanent file system (optional)
        // destFilename - new name of file (optional - otherwise uses current filename)
        // 1. Request temporary file system 
        //
        function moveFileToPersistentStorage(srcPath, destDir, destFilename) {
           // Connvert path to filename
           var srcFilename = srcPath.replace(/^.*[\\\/]/, '');
           console.log("in moveFileToPersistentStorage...");
           // Request persistent file system (to copy to)
           window.requestFileSystem(
                LocalFileSystem.TEMPORARY, 
                0, 
                function(fst) {
                    fsCopy(fst.root, srcFilename, destDir, destFilename);
                    console.log("calling fsCopy...");
                }, 
                onFileSystemFail
            );
        }
           
           
        // Phonegap device impage capture
        navigator.device.capture.captureImage(
            // success callback
            function(mediaFiles){
                console.log("captured image. Now lets make it permanent...");
                moveFileToPersistentStorage(mediaFiles[0].fullPath,'assets/images',null);
            },
            // fail callback
            function(evt) {
                // Make this an alert
                var msg = 'An error occurred during capture: ' + evt.target.error.code;
                navigator.notification.alert(msg, null, 'Capture error');
            },
            {limit: 1}
        );
    },
           
    // Audio Record
    //
    onAudioRecordTap: function() {
        // Launch device audio recording application
        navigator.device.capture.captureAudio(
            // Capture success callback
            function(mediaFiles){
                console.log ("captured audio");
                // check that an mp4 file with this name doesn't already exist. If it does, delete it
                window.requestFileSystem(
                    LocalFileSystem.TEMPORARY, 
                    0, 
                    // Request file system success callback
                    function(fileSystem){
                        // remove .wav extension and add .mp4 extension - this is the file that the converter will create
                        console.log("just before convertedAudioFilename is created");
                        var convertedAudioFilename = mediaFiles[0].name.replace(/\.[^\.]*$/, '.m4a');
                        console.log ("convertedAudioFilename = " + convertedAudioFilename);
                                                                          
                        // check if the file that the converter will create already exists, and delete it if it does
                        fileSystem.root.getFile(
                            convertedAudioFilename, 
                            { create: false, exclusive: false }, 
                            // FileSystem Success callback (found file) 
                            function success(entry) {
                                // delete file entry
                                console.log("found file, deleting it");
                                // add call backs here?
                                entry.remove();
                                //window.plugins.AudioEncode.encodeAudio(mediaFiles[0].fullPath, "successfulAudioEncode", "failedAudioEncode");
                            },
                            // FileSystem fail callback
                            function fail() {
                                console.log("didn't find file");
                                // if we can't find file, assume it doesn't exist and everything is OK
                                window.plugins.AudioEncode.encodeAudio(mediaFiles[0].fullPath, "successfulAudioEncode", "failedAudioEncode");
                            }
                        );      
                    }, 
                    // Request file system error callback
                    onFileSystemFail
                );
                                                 
            },
            // Capture error callback
            function(error){
                var msg = 'An error occurred during capture: ' + error.code;
                navigator.notification.alert(msg, null, 'Capture error');
            },
            {limit: 1}
        );
    }
});
